package main

import (
	"editor/constant"
	"editor/service/mdFile"
	_ "editor/store"
	"editor/utils"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io/ioutil"
	"log"
	"net/url"
	"regexp"
	"strings"
)

var bucket *oss.Bucket

/**
 * 定时清理oss上未被使用的文件
 */
func main() {

	fileInCons, err := getFilesInCons()
	if err != nil {
		log.Fatal("获取md文件内容内使用的文件列表失败", err)
	}

	if len(fileInCons) == 0 {
		log.Fatal("获取文件内使用的文件列表为空")
	}

	ossExistsFile, err := getOssExistsFiles()
	if err != nil {
		log.Fatal("获取oss上文件列表失败", err)
	}
	if len(ossExistsFile) == 0 {
		log.Fatal("获取OSS上文件列表为空")
	}

	for _, consFile := range ossExistsFile {
		if !utils.StringInArray(consFile, fileInCons) {
			fmt.Println("文件未被使用[删除]: ", consFile)

			err = deleteObject(consFile)
			if err != nil {
				log.Fatal("bucket.DeleteObject failed:", err)
			}

		}
	}
}

func deleteObject(objectName string) (err error) {
	bucket, err = getOssBucket()
	if err != nil {
		return
	}

	return bucket.DeleteObject(objectName)
}

func getOssBucket() (*oss.Bucket, error) {
	if bucket != nil {
		return bucket, nil
	}
	cnf := constant.Config.ALiYunOss
	client, err := oss.New(cnf.Endpoint, cnf.AccessKey, cnf.AccessSecret)
	if err != nil {
		err = fmt.Errorf("oss.New failed:%v", err)
		return nil, err
	}

	bucket, err := client.Bucket(cnf.BucketName)
	if err != nil {
		err = fmt.Errorf("get client.Bucket failed:%v", err)
		return nil, err
	}
	return bucket, nil
}

func getOssExistsFiles() (ossExistsFile []string, err error) {

	bucket, err = getOssBucket()
	if err != nil {
		return
	}

	objArr, err := bucket.ListObjects()
	if err != nil {
		err = fmt.Errorf("get bucket.ListObjects failed:%v", err)
		return
	}

	for _, m := range objArr.Objects {
		ossExistsFile = append(ossExistsFile, m.Key)
	}
	return
}

func getFilesInCons() (arrFile []string, err error) {
	baseDir := constant.MDFileDir
	parse := func(parentDir string, item *constant.MDFile) error {
		var filePath string
		if parentDir == "" {
			filePath = baseDir + "/" + item.FileName
		} else {
			filePath = baseDir + "/" + parentDir + "/" + item.FileName
		}

		data, err := ioutil.ReadFile(filePath)
		if err != nil {
			return fmt.Errorf("获取文件[%s]的内容失败 error:%v", filePath, err)
		}

		all := regexp.MustCompile(`!\[[^\]]*\]\(([^\)]*)\)`).FindAllStringSubmatch(string(data), -1)
		for _, i := range all {
			tmp := strings.Split(i[1], " ")
			curUrl := tmp[0]
			parsedUrl, err := url.Parse(curUrl)
			if err != nil {
				return fmt.Errorf("无法解析URL,error:%v", err)
			}

			arrFile = append(arrFile, parsedUrl.Path[1:])
		}
		return nil
	}

	for _, li := range mdFile.MDFileList {
		if li.IsDir == 1 {
			for _, subLi := range li.ChildList {
				err = parse(li.Name, subLi)
				if err != nil {
					return
				}
			}
		} else {
			err = parse("", li)
			if err != nil {
				return
			}
		}
	}

	return
}
